﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using ERCS.ViewModel.Reports.CsseVMs;
using System.IO;
using System.Collections.Generic;
using ERCS.Model;
using Microsoft.AspNetCore.Mvc.Formatters;
using System.Globalization;
using ERCS.DataAccess;
using System.Linq.Dynamic.Core;
using Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore;

namespace ERCS.Controllers
{
    [Area("Reports")]
    [ActionDescription("世界疫情数据")]
    [FixConnection(CsName = "csse")]
    public partial class CsseController : BaseController
    {
        #region 搜索
        [ActionDescription("搜索")]
        public ActionResult Index()
        {
            var vm = CreateVM<CsseListVM>();
            return PartialView(vm);
        }

        [ActionDescription("搜索")]
        [HttpPost]
        public string Search(CsseListVM vm)
        {
            return vm.GetJson(false);
        }

        #endregion

        #region 新建
        [ActionDescription("新建")]
        public ActionResult Create()
        {
            var vm = CreateVM<CsseVM>();
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("新建")]
        public ActionResult Create(CsseVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                vm.DoAdd();
                if (!ModelState.IsValid)
                {
                    vm.DoReInit();
                    return PartialView(vm);
                }
                else
                {
                    return FFResult().CloseDialog().RefreshGrid();
                }
            }
        }
        #endregion

        #region 修改
        [ActionDescription("修改")]
        public ActionResult Edit(string id)
        {
            var vm = CreateVM<CsseVM>(id);
            return PartialView(vm);
        }

        [ActionDescription("修改")]
        [HttpPost]
        [ValidateFormItemOnly]
        public ActionResult Edit(CsseVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                vm.DoEdit();
                if (!ModelState.IsValid)
                {
                    vm.DoReInit();
                    return PartialView(vm);
                }
                else
                {
                    return FFResult().CloseDialog().RefreshGridRow(vm.Entity.ID);
                }
            }
        }
        #endregion

        #region 删除
        [ActionDescription("删除")]
        public ActionResult Delete(string id)
        {
            var vm = CreateVM<CsseVM>(id);
            return PartialView(vm);
        }

        [ActionDescription("删除")]
        [HttpPost]
        public ActionResult Delete(string id, IFormCollection nouse)
        {
            var vm = CreateVM<CsseVM>(id);
            vm.DoDelete();
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid();
            }
        }
        #endregion

        #region 详细
        [ActionDescription("详细")]
        public ActionResult Details(string id)
        {
            var vm = CreateVM<CsseVM>(id);
            return PartialView(vm);
        }
        #endregion

        #region 批量修改
        [HttpPost]
        [ActionDescription("批量修改")]
        public ActionResult BatchEdit(string[] IDs)
        {
            var vm = CreateVM<CsseBatchVM>(Ids: IDs);
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("批量修改")]
        public ActionResult DoBatchEdit(CsseBatchVM vm, IFormCollection nouse)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return PartialView("BatchEdit", vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert("操作成功，共有" + vm.Ids.Length + "条数据被修改");
            }
        }
        #endregion

        #region 批量删除
        [HttpPost]
        [ActionDescription("批量删除")]
        public ActionResult BatchDelete(string[] IDs)
        {
            var vm = CreateVM<CsseBatchVM>(Ids: IDs);
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("批量删除")]
        public ActionResult DoBatchDelete(CsseBatchVM vm, IFormCollection nouse)
        {
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return PartialView("BatchDelete", vm);
            }
            else
            {
                return FFResult().CloseDialog().RefreshGrid().Alert("操作成功，共有" + vm.Ids.Length + "条数据被删除");
            }
        }
        #endregion

        #region 导入
        [ActionDescription("导入")]
        public ActionResult Import()
        {
            var vm = CreateVM<CsseImportVM>();
            return PartialView(vm);
        }

        [HttpPost]
        [ActionDescription("导入")]
        public ActionResult Import(CsseImportVM vm, IFormCollection nouse)
        {
            byte[] fdata = null;
            using (var newdc = ConfigInfo.ConnectionStrings[0].CreateDC())
            {
                fdata = FileHelper.GetFileByteForDownLoadById(vm.UploadFileId.Value, newdc, ConfigInfo);
            }
            MemoryStream ms = new MemoryStream(fdata);
            StreamReader sr = new StreamReader(ms);
            string title = sr.ReadLine();
            string[] cols = title.Split(",");
            int count = 0;
            try
            {
                while (true)
                {
                    string line = sr.ReadLine();
                    count++;
                    if (string.IsNullOrEmpty(line))
                    {
                        break;
                    }
                    string[] data = line.Split(",");

                    for (int i = 4; i < cols.Length; i++)
                    {
                        var col = cols[i];
                        Csse csse = new Csse();
                        csse.Province = data[0];
                        csse.Country = data[1];
                        csse.Lat = double.Parse(data[2]);
                        csse.Long = double.Parse(data[3]);
                        csse.Date = DateTime.Parse(col, new CultureInfo("en_US"));
                        csse.ConfirmedCase = int.Parse(data[i]);

                        DC.Set<Csse>().Add(csse);
                    }
                }
                DC.SaveChanges();
            }
            catch (Exception ex)
            {
                vm.ErrorListVM.EntityList.Add(new ErrorMessage { ExcelIndex = count, Message = ex.ToString(), Index = count });
                return PartialView(vm);
            }
            return FFResult().CloseDialog().RefreshGrid().Alert("成功导入 " + count.ToString() + " 行数据");
        }
        #endregion

        [ActionDescription("导出")]
        [HttpPost]
        public IActionResult ExportExcel(CsseListVM vm)
        {
            vm.SearcherMode = vm.Ids != null && vm.Ids.Count > 0 ? ListVMSearchModeEnum.CheckExport : ListVMSearchModeEnum.Export;
            var data = vm.GenerateExcel();
            return File(data, "application/vnd.ms-excel", $"Export_Csse_{DateTime.Now.ToString("yyyy-MM-dd")}.xls");
        }

    }
}
